import React, { useState, useEffect } from 'react';
import { Button, Select, Input, Avatar } from 'antd';
import { UserOutlined, RobotOutlined, AudioOutlined, WifiOutlined } from '@ant-design/icons';
import CustomButton from './CustomButton';
import styles from './ChatPanel.less';

const { TextArea } = Input;

interface Message {
  id: string;
  type: 'user' | 'assistant';
  contentType: 'text' | 'voice';
  content: string;
  timestamp: Date;
  sender: string;
  avatar?: string;
}

const ChatPanel: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      type: 'assistant',
      contentType: 'text',
      content: '智能助手为你服务,请输入您的问题。',
      timestamp: new Date(),
      sender: '智能助手',
    },
  ]);
  const [inputValue, setInputValue] = useState('');
  const [isVoiceMode, setIsVoiceMode] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null);
  const [audioChunks, setAudioChunks] = useState<Blob[]>([]);
  const [audioUrls, setAudioUrls] = useState<Map<string, string>>(new Map());
  const [recordingDuration, setRecordingDuration] = useState(0);
  const [recordingTimer, setRecordingTimer] = useState<NodeJS.Timeout | null>(null);
  const [pendingAudioBlob, setPendingAudioBlob] = useState<Blob | null>(null);
  const [showPendingActions, setShowPendingActions] = useState(false);

  // 智能回复的随机回复
  const getRandomReply = () => {
    const replies = [
      '我理解您的问题，让我为您详细解答。',
      '这是一个很好的问题，根据我的分析，建议您...',
      '感谢您的提问，关于这个问题，我认为...',
      '您提到的这个情况很常见，通常的处理方法是...',
      '根据您提供的信息，我建议您可以考虑以下几个方面...',
      '这个问题涉及到多个方面，让我为您逐一分析...',
      '我明白您的担忧，让我为您提供一些建议...',
      '基于您的情况，我推荐以下解决方案...',
    ];
    return replies[Math.floor(Math.random() * replies.length)];
  };

  const handleSendMessage = () => {
    if (inputValue.trim()) {
      const userMessage: Message = {
        id: Date.now().toString(),
        type: 'user',
        contentType: 'text',
        content: inputValue,
        timestamp: new Date(),
        sender: '用户',
      };
      
      // 添加用户消息
      setMessages(prev => [...prev, userMessage]);
      setInputValue('');
      
      // 模拟AI回复延迟
      setTimeout(() => {
        const assistantMessage: Message = {
          id: (Date.now() + 1).toString(),
          type: 'assistant',
          contentType: 'text',
          content: getRandomReply(),
          timestamp: new Date(),
          sender: '智能助手',
        };
        setMessages(prev => [...prev, assistantMessage]);
      }, 1000);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const toggleVoiceMode = () => {
    setIsVoiceMode(!isVoiceMode);
  };

  const handleVoiceMessage = (audioBlob: Blob) => {
    const messageId = Date.now().toString();
    const audioUrl = URL.createObjectURL(audioBlob);
    
    // 保存音频URL
    setAudioUrls(prev => new Map(prev).set(messageId, audioUrl));
    
    const userMessage: Message = {
      id: messageId,
      type: 'user',
      contentType: 'voice',
      content: formatDuration(recordingDuration),
      timestamp: new Date(),
      sender: '用户',
    };
    
    // 添加用户语音消息
    setMessages(prev => [...prev, userMessage]);
    
    // 模拟AI回复延迟
    setTimeout(() => {
      const assistantMessage: Message = {
        id: (Date.now() + 1).toString(),
        type: 'assistant',
        contentType: 'text',
        content: '我收到了您的语音消息，让我为您分析一下...',
        timestamp: new Date(),
        sender: '智能助手',
      };
      setMessages(prev => [...prev, assistantMessage]);
    }, 1500);
  };

  const playAudio = (messageId: string) => {
    const audioUrl = audioUrls.get(messageId);
    if (audioUrl) {
      const audio = new Audio(audioUrl);
      audio.play().catch(error => {
        console.error('播放音频失败:', error);
      });
    }
  };

  const startRecordingTimer = () => {
    setRecordingDuration(0);
    const timer = setInterval(() => {
      setRecordingDuration(prev => prev + 1);
    }, 1000);
    setRecordingTimer(timer);
  };

  const stopRecordingTimer = () => {
    if (recordingTimer) {
      clearInterval(recordingTimer);
      setRecordingTimer(null);
    }
  };

  const formatDuration = (seconds: number) => {
    return `${seconds}s`;
  };

  const sendVoiceMessage = () => {
    if (pendingAudioBlob) {
      handleVoiceMessage(pendingAudioBlob);
      setPendingAudioBlob(null);
      setShowPendingActions(false);
      setRecordingDuration(0);
    }
  };

  const cancelVoiceMessage = () => {
    setPendingAudioBlob(null);
    setShowPendingActions(false);
    setRecordingDuration(0);
  };

  const toggleRecording = async () => {
    if (!isRecording) {
      try {
        // 请求麦克风权限
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        
        // 创建MediaRecorder
        const recorder = new MediaRecorder(stream);
        const chunks: Blob[] = [];
        
        recorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            chunks.push(event.data);
          }
        };
        
        recorder.onstop = () => {
          const audioBlob = new Blob(chunks, { type: 'audio/wav' });
          console.log('录音完成，音频大小:', audioBlob.size);
          
          // 设置预发送状态
          setPendingAudioBlob(audioBlob);
          setShowPendingActions(true);
          
          // 停止所有音频轨道
          stream.getTracks().forEach(track => track.stop());
        };
        
        recorder.onerror = (event) => {
          console.error('录音错误:', event);
        };
        
        setMediaRecorder(recorder);
        setAudioChunks(chunks);
        recorder.start();
        setIsRecording(true);
        startRecordingTimer();
        
        console.log('开始录音...');
      } catch (error) {
        console.error('无法访问麦克风:', error);
        let errorMessage = '无法访问麦克风';
        
        if (error instanceof Error) {
          if (error.name === 'NotAllowedError') {
            errorMessage = '麦克风权限被拒绝，请在浏览器设置中允许麦克风访问';
          } else if (error.name === 'NotFoundError') {
            errorMessage = '未找到麦克风设备';
          } else if (error.name === 'NotSupportedError') {
            errorMessage = '浏览器不支持录音功能';
          }
        }
        
        alert(errorMessage);
      }
    } else {
      // 停止录音
      if (mediaRecorder && mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
        setIsRecording(false);
        stopRecordingTimer();
        console.log('停止录音...');
      }
    }
  };

  // 组件卸载时清理录音资源和音频URL
  useEffect(() => {
    return () => {
      if (mediaRecorder && mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
      }
      // 清理所有音频URL
      audioUrls.forEach(url => URL.revokeObjectURL(url));
    };
  }, [mediaRecorder, audioUrls]);

  return (
    <div className={styles.chatContainer}>
      <div className={styles.messagesContainer}>
        {messages.map((message) => (
          <div 
            key={message.id} 
            className={`${styles.message} ${styles[message.type]}`}
          >
            {message.type === 'assistant' && (
              <Avatar 
                className={styles.avatar}
                icon={<RobotOutlined />}
                style={{ 
                  backgroundColor: '#52c41a' 
                }}
              />
            )}
            <div className={`${styles.messageBubble} ${styles[message.type]}`}>
              {message.type === 'assistant' && (
                <div className={styles.assistantName}>智能助手</div>
              )}
              <div className={styles.messageContent}>
                {message.contentType === 'voice' ? (
                  <div className={styles.voiceMessage}   onClick={() => playAudio(message.id)}>
                    <span className={styles.voiceDuration}>{message.content}</span>
                     <div style={{fontSize: 20, rotate: '-90deg'}}><WifiOutlined /></div>
                    {/* <Button 
                      type="link" 
                      size="small"
                      onClick={() => playAudio(message.id)}
                      className={styles.playButton}
                      icon={<WifiOutlined />}
                    /> */}
                  </div>
                ) : (
                  message.content
                )}
                <div className={styles.messageTime}>
                  {message.timestamp.toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                  })}
                </div>
              </div>
            </div>
            {message.type === 'user' && (
              <Avatar 
                className={`${styles.avatar} ${styles.userAvatar}`}
                icon={<UserOutlined />}
                style={{ 
                  backgroundColor: '#FFD700' 
                }}
              />
            )}
          </div>
        ))}
      </div>

      <div className={styles.inputContainer}>
        {!isVoiceMode ? (
          <>
            <TextArea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="请输入内容"
              className={styles.messageInput}
            />
            <div className={styles.inputActions}>
              <Button 
                type="link" 
                className={styles.voiceButton}
                onClick={toggleVoiceMode}
              >
                切换至语音模式
              </Button>
            </div>
          </>
        ) : showPendingActions ? (
          <div className={styles.pendingActions}>
            {/* <div className={styles.recordingPreview}>
              <span className={styles.recordingDuration}>{formatDuration(recordingDuration)}</span>
              <AudioOutlined className={styles.recordingIcon} />
            </div> */}
            <div className={styles.actionButtons}>
              <CustomButton
                text="发送语音"
                onClick={sendVoiceMessage}
                type="primary"
                icon="send"
                className={styles.sendButton}
              />
              <CustomButton
                text="取消"
                onClick={cancelVoiceMessage}
                type="default"
                className={styles.cancelButton}
              />
            </div>
            <div className={styles.inputActions}>
              <Button 
                type="link" 
                className={styles.voiceButton}
                onClick={toggleVoiceMode}
              >
                切换至文字模式
              </Button>
            </div>
          </div>
        ) : (
          <>
            <CustomButton
              text={isRecording ? "结束识别" : "开始识别"}
              icon={isRecording ? "pause" : "play"}
              onClick={toggleRecording}
              fullWidth={true}
            />
            <div className={styles.inputActions}>
              <Button 
                type="link" 
                className={styles.voiceButton}
                onClick={toggleVoiceMode}
              >
                切换至文字模式
              </Button>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default ChatPanel;
